import { query, addMenu } from '@services/system/menu';
import { listToTree } from '@utils/utils';

export default {
  namespace: 'menu',

  state: {
    data: {
      list: [],
      pagination: {},
    },
    treeData: {},
  },

  effects: {
    *fetch(_, { call, put }) {
      const { data } = yield call(query, { page: 1, size: 100 });
      data.list = listToTree(data.list, {
        idKey: 'id',
        parentKey: 'parent_id',
      });
      yield put({
        type: 'save',
        payload: data,
      });
    },

    *fetchTreeData(_, { call, put }) {
      let { data: { list } } = yield call(query, { page: 1, size: 1000 });
      list = list.map(item => {
        return {
          title: item.name,
          value: item.id,
          key: item.id,
          ...item,
        };
      });
      list = listToTree(list, {
        idKey: 'id',
        parentKey: 'parent_id',
      });
      yield put({
        type: 'saveTreeData',
        payload: list,
      });
    },

    *add({ payload, callback }, { call }) {
      const { code } = yield call(addMenu, { ...payload });
      if (code === 0) {
        if (callback) callback();
      }
    },

    *update({ payload, callback }, { call }) {
      const { code } = yield call(addMenu, { ...payload });
      if (code === 0) {
        if (callback) callback();
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    saveTreeData(state, action) {
      return {
        ...state,
        treeData: action.payload,
      };
    },
  },
};
